package com.example.wotu;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Pattern;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link FragWLBook.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link FragWLBook#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FragWLBook extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private View view;
    private ArrayList<String> bookname,bookurl,urlbookWL,urlbookWLlj,XUX;
    private ArrayAdapter aapt;
    private ArrayAdapter sinn;
    private ListView book;
    private Spinner spinner;
    private Spinner spinne;
    private Handler handler;
    private String url = null,wurl = null;
    private Fragment wlopen;
    private FrameLayout wlcont;
    private LinearLayout wlfg;
    private LinearLayout jmsel;

    public FragWLBook() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FragWLBook.
     */
    // TODO: Rename and change types and number of parameters
    public static FragWLBook newInstance(String param1, String param2) {
        FragWLBook fragment = new FragWLBook();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        //******* 101 *******
        view = inflater.inflate(R.layout.frag_wl_book, container, false);
        mListener.onNOT_WK(101);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        getFind();
        getSinnpe(0);
        GETOnClick();
    }

    //需要增加设计只有搜索才有对应数据
    // ****（不管哪个网站，解析后的数据都要保存到 bookname , bookurl 编译统一管理）****
    //1.实例id；2.填充下拉框；3.链接数据（jsoup返回数据很快，但在放到ListView就很慢了）；4.隐藏；5.点击
    private void getFind(){
        bookname = new ArrayList<>();
        bookurl = new ArrayList<>();
        book = (ListView) view.findViewById(R.id.booklist);
        spinner = (Spinner) view.findViewById(R.id.spinner);
        spinne = (Spinner) view.findViewById(R.id.spinne);
        wlcont = view.findViewById(R.id.WLcontext);
        wlfg = view.findViewById(R.id.wlFG);
        jmsel = view.findViewById(R.id.JMsel);
    }
    private void getSinnpe(int s){
        if(s == 0){
            XUX = new ArrayList<>();
            XUX.add("精准查询");
            XUX.add("模糊查询");
            XUX.add("全部小说");
            ArrayAdapter sin =  new ArrayAdapter(getActivity(),R.layout.support_simple_spinner_dropdown_item,XUX);
            spinne.setAdapter(sin);
        }
        else if(s == 1){
            urlbookWL = new ArrayList<>();
            urlbookWLlj = new ArrayList<>();
            urlbookWL.add("笔趣阁");
            urlbookWLlj.add("https://www.xbiquge.la/xiaoshuodaquan/");
            sinn = new ArrayAdapter(getActivity(),R.layout.support_simple_spinner_dropdown_item,urlbookWL);
            spinner.setAdapter(sinn);
        }
    }
    private void getDataRUNN(){
        //jsoup 是一款Java 的HTML解析器，可直接解析某个URL地址、HTML文本内容。
        //它提供了一套非常省力的API，可通过DOM，CSS以及类似于jQuery的操作方法来取出和操作数据。
        //这个是子线程（以后这里的链接读写到SQL数据库里面）

        //笔趣阁 199 亲亲小说网
        //原版（前期先手动注入下拉框数据，因每个网站的样式结构不一致，导致数据有问题）
        url = urlbookWLlj.get(0);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Document document = null;
                try {
                    int isn = 0;
                    document = Jsoup.connect(url).get();
                    Element content = document.getElementById("main");
                    Elements links = content.getElementsByTag("a");
                    for (Element link : links) {
                        //为：链接地址；名字
                        String linkHref = link.attr("href");
                        String linkText = link.text();
                        bookname.add(linkText);
                        bookurl.add(linkHref);
                    }
                    handler.sendMessage(handler.obtainMessage(0));
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
            }
        };
        //因为是子线程的原因，后台运行导致主线程这里的bookname是没有数据的。所以要这样做：
        //在第一个线程执行完后，保存一个数据，然后运行时的第二线程等待到来的数据然后执行 ListView 添加
        //也可以使用 AsyncTask 解决
        new Thread(runnable).start();
        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if(msg.what == 0){
                    aapt = new ArrayAdapter(getActivity(),R.layout.support_simple_spinner_dropdown_item,bookname);
                    book.setAdapter(aapt);
                }
            }
        };
    }
    private void Yinc(){
        spinner.setVisibility(View.GONE);
        jmsel.setVisibility(View.GONE);
    }
    private void GETOnClick(){
        //章节的点击事件
        book.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(wurl == null){
                    wurl = bookurl.get(i);
                    wlopen = new FragWLOpenBook();
                }else{
                    if(!wurl.equals(bookurl.get(i))) wlopen = new FragWLOpenBook();
                }
                wlfg.setVisibility(View.GONE);
                wlcont.setVisibility(View.VISIBLE);
                Bundle LJ = new Bundle();
                LJ.putInt("num",1);
                LJ.putString("LV",bookurl.get(i));
                wlopen.setArguments(LJ);
                getChildFragmentManager().beginTransaction().replace(R.id.WLcontext,wlopen).commitAllowingStateLoss();
            }
        });
        //左下拉框事件
        spinne.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Yinc();
                if(i == 0 || i == 1){
                    jmsel.setVisibility(View.VISIBLE);
//                    Toast.makeText(getActivity(),"暂时还未开发！因缺少数据库！",Toast.LENGTH_SHORT).show();
                }
                else if(i == 2){
                    spinner.setVisibility(View.VISIBLE);
                    getSinnpe(1);
                    getDataRUNN();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
        void onNOT_WK(int wk);
    }
}
